

import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_baidu_mapapi_search/flutter_baidu_mapapi_search.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:sph_shipper/AppConfig/Config.dart';

import '../AppConfig/LocalStorage.dart';
import '../http/api.dart';
import 'LoadingAddressView.dart';

class MapSiteSelection extends StatefulWidget {
  const MapSiteSelection({super.key, required this.nowLocMap});
  final Map nowLocMap;
  @override
  State<MapSiteSelection> createState() => _MapSiteSelectionState();
}

class _MapSiteSelectionState extends State<MapSiteSelection> {

  /// 我的位置
  BMFUserLocation? _userLocation;

  /// 定位模式
  BMFUserTrackingMode _userTrackingMode = BMFUserTrackingMode.Follow;
  List editMapList=['',''];
  int chooseIndex=0;
  List searchAddressList=[];
  Map detailMap={};
  String detailAddress="";
  Map nowLocMap={};
  BMFMapController? _mapController;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    nowLocMap=widget.nowLocMap;

  }
  /// 创建完成回调
  @override
  void onBMFMapCreated(BMFMapController controller) {
    _mapController = controller;

    controller.setMapClickedMarkerCallback(callback: (BMFMarker marker) {
      print('marker点击----${marker.id}');

    });
    /// 地图加载回调
    controller.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');

      controller.showUserLocation(true);
      updateUserLocation(controller);
      controller.setUserTrackingMode(_userTrackingMode);
    });
    controller.setMapRegionDidChangeCallback(
        callback: (BMFMapStatus mapStatus) {

          Map data = mapStatus.toMap();

          getLocation(data['targetGeoPt']['latitude'], data['targetGeoPt']['longitude']);

          // updateUserLocation(controller);
        });

  }
  void updateMapCenter(double newLatitude, double newLongitude) {
    if (_mapController != null) {
      _mapController!.setCenterCoordinate(
          BMFCoordinate(newLatitude, newLongitude),
          true
      );
    }
  }

  /// 更新位置
  void updateUserLocation(BMFMapController controller) {
     BMFCoordinate coordinate = BMFCoordinate(nowLocMap['location']['lat'] ,nowLocMap['location']['lng']);

    // BMFCoordinate coordinate = BMFCoordinate(31.374060890358 , 120.74716975649);
    BMFLocation location = BMFLocation(

        coordinate: coordinate,
        altitude: 0,
        horizontalAccuracy: 5,
        verticalAccuracy: -1.0,
        speed: -1.0,
        course: -1.0);
    BMFUserLocation userLocation = BMFUserLocation(
      location: location,
    );
    _userLocation = userLocation;
    controller.updateLocationData(_userLocation!);
  }
  @override
  BMFMapOptions initMapOptions() {
    BMFMapOptions mapOptions = BMFMapOptions(
      gesturesEnabled:true,
      scrollEnabled: true,
      // center: BMFCoordinate(31.374060890358 , 120.74716975649),
       center: BMFCoordinate(widget.nowLocMap['location']['lat'] ,widget.nowLocMap['location']['lng']),
      zoomLevel: 10,
      maxZoomLevel: 18,
      minZoomLevel: 15,
      mapPadding: BMFEdgeInsets(top: 0, left: 50, right: 50, bottom: 0),
    );
    return mapOptions;
  }
  @override
  void dispose() {
    super.dispose();
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }
  void onMapMoveEnd(Map<String, dynamic> result) {
    BMFCoordinate centerCoordinate =
    BMFCoordinate.fromMap(result['target']); // 获取地图中心点坐标

  }

    DateTime? _lastCallTime;

    void getLocation(double latitude, double longitude) async {
      // 定义节流的时间间隔，比如5秒
      const int throttleSeconds = 5;

      // 获取当前时间
      DateTime now = DateTime.now();

      // 检查是否满足节流条件
      if (_lastCallTime != null && now.difference(_lastCallTime!).inSeconds < throttleSeconds) {

        return; // 如果没有超过指定的时间间隔，则直接返回
      }

      // 更新上次调用时间
      _lastCallTime = now;
    String? token =await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    //nmk6gFoaaPXmiWx1GEkqGD4e5GIogdUT  Pb9qx5M4d02snVGSQaEqGVpqybA18AS8  0t6rhRWUGmqtbsMRMBVSqzbBwBrCzXLj
    dio.get<String>("https://api.map.baidu.com/reverse_geocoding/v3/?ak=Pb9qx5M4d02snVGSQaEqGVpqybA18AS8&output=json&coordtype=wgs84ll&location=$latitude,$longitude")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['status'].toString();
        if (code == "0") {
          var nowAddressMap=jsonMap['result'];


          if(editMapList[0]!=""){
            setState(() {
              editMapList[1]=nowAddressMap;
            });
          }else{
            setState(() {
              editMapList[0]=nowAddressMap;
              editMapList[1]=nowAddressMap;
            });
          }

        } else {

        }

      });
    }).catchError((error) {
      print(error);
    });
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        leading: IconButton(icon: Icon(Icons.arrow_back_ios,color: Colors.black,),onPressed: (){Navigator.pop(context);},),

        centerTitle: true,
        backgroundColor: Colors.white,
        title:
        GestureDetector(
          child:   Container(
            width:220.w,
            height: 30.h,
            decoration: BoxDecoration(
                color: MyColors.backgreyColor,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child:Center(
              child:   detailAddress==""?
              Text("请输入详细地址",style: TextStyle(color: MyColors.hintColor,fontSize: 14.sp),)
                  :Text(detailAddress,overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.black,fontSize: 14.sp),),
            ),
          ),
          onTap: ()async{
            final result=await showModalBottomSheet(context: context, builder: (BuildContext context) {
              return checkDetialAddressSheet(region: '',
              );});
            if (result !=null){
              setState(() {
                detailMap=result;
                detailAddress=detailMap['name'];
                nowLocMap['location']['lat']=double.parse(detailMap['location']['lat']);
                nowLocMap['location']['lng']=double.parse(detailMap['location']['lng']);
                getLocation(nowLocMap['location']['lat'],nowLocMap['location']['lng']);
                updateMapCenter(nowLocMap['location']['lat'],nowLocMap['location']['lng']);
              });
            }
          },
        ),

      ),


      body: Column(
        children: [
      Expanded(
      child: Stack(
      children: [

        Container(
          width: screenSize.width,
          height: screenSize.height-140.h,
          child:       BMFMapWidget(
            onBMFMapCreated: (mapController) {
              onBMFMapCreated(mapController);
            },

            mapOptions: initMapOptions(),
          ),
        ),
        Center(
          child: Icon(Icons.edit_location,color: Colors.red,size:40,),
        ),
      ],
        alignment: Alignment.center,
      ),

      ),
        if( editMapList[0]!="")
    Container(
      height: 140.h,
      child:
      ListView.builder(
      shrinkWrap:false,
    itemCount:2,
    itemBuilder: (BuildContext context, int index) {
        return GestureDetector(
          child:    Container(
            padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
            child:Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: screenSize.width-100.w,
                      child:  Text(editMapList[index]['formatted_address'],style: TextStyle(color: Colors.black,fontSize: 16.sp)),
                    ),
                    Container(
                      width: screenSize.width-80.w,
                      child:    Text(editMapList[index]['addressComponent']['province']+editMapList[index]['addressComponent']['city']+
                          editMapList[index]['addressComponent']['district']+editMapList[index]['addressComponent']['town'],style: TextStyle(color: MyColors.authTipColor,fontSize: 14.sp),),
                    ),

                    Divider(height: 16.h,color: MyColors.backgreyColor,),
                  ],
                ),
                IconButton(onPressed: (){
                }, icon: Icon(Icons.done,color: chooseIndex==index?MyColors.themeColor:Colors.white,size: 30,) ),
              ],
            )

          ),
          onTap: (){
            setState(() {
              chooseIndex=index;
            });

          },
        );

    }
    ),
    ),
        GestureDetector(
          child:  Container(
            margin: EdgeInsets.only(left: 10.w,right: 10.w,bottom: 20.h),
            height: 40.h,
            decoration: BoxDecoration(
                color: MyColors.themeColor,
                borderRadius: BorderRadius.all(Radius.circular(30))),
            child: Center(child: Text("设为地址",style: TextStyle(color: Colors.white,fontSize: 16.sp,fontWeight: FontWeight.w600),),),
          ),
          onTap: (){
            Navigator.pop(context,editMapList[chooseIndex]);
          },
        ),

        ],
      ),
    );
  }
}
